package com.neborosoft.android.gui.adapters.listview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import com.neborosoft.android.gui.views.HighlightableLinearLayout;

/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 06.11.12
 * Time: 2:10
 * To change this template use File | Settings | File Templates.
 */
public abstract class SelectableViewArrayAdapter<Element,ViewHolder>
        extends ViewArrayAdapter<Element,ViewHolder>
{
    private int currentSelectedIndex = -1;

    public int getCurrentSelectedIndex() {
        return currentSelectedIndex;
    }

    public Element getCurrentSelectedElement(){
        return getElement(currentSelectedIndex);
    }

    public boolean isItemSelected(){
        return currentSelectedIndex >= 0;
    }

    protected void setCurrentSelectedIndex(int currentSelectedIndex) {
        if(currentSelectedIndex == this.currentSelectedIndex){
            return;
        }

        AbsListView parent = getParentListView();
        if(parent.getAdapter() != this){
            this.currentSelectedIndex = currentSelectedIndex;
            return;
        }

        HighlightableLinearLayout view;

        if(this.currentSelectedIndex >= 0){
            view = (HighlightableLinearLayout)getView(this.currentSelectedIndex);
            if(view != null){
                view.setHighlighted(false);
            }
        }

        if(currentSelectedIndex >= 0){
            view = (HighlightableLinearLayout)getView(currentSelectedIndex);
            if(view != null){
                view.setHighlighted(true);
            }
        }

        this.currentSelectedIndex = currentSelectedIndex;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = super.getView(position, convertView, parent);

        if(getItemViewType(position) == NULL_VIEW_TYPE){
            return convertView;
        }

        HighlightableLinearLayout view = (HighlightableLinearLayout)convertView;

        if(position == getCurrentSelectedIndex()){
            view.setHighlighted(true);
        }
        else{
            view.setHighlighted(false);
        }

        return view;
    }

    @Override
    protected void onItemClick(Element element, View view, int position) {
        setCurrentSelectedIndex(position);
        super.onItemClick(element, view, position);
    }

    public void scrollListViewToSelectedIndex(){
        int selectedIndex = getCurrentSelectedIndex();
        if(selectedIndex == 0){
            selectedIndex = 1;
        }

        AbsListView listView = getParentListView();
        listView.setSelection(selectedIndex - 1);
    }

    protected SelectableViewArrayAdapter(Context context, AbsListView parent) {
        super(context, parent);
    }
}
